/*
 * XMLProcessingView.java
 */

package xmlprocessing;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Locale;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 * The application's main frame.
 */
public class XMLProcessingView extends FrameView {

    public XMLProcessingView(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = XMLProcessingApp.getApplication().getMainFrame();
            aboutBox = new XMLProcessingAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        XMLProcessingApp.getApplication().show(aboutBox);
    }
    void excelSet() {
        WorkbookSettings ws = new WorkbookSettings();
        jxl.write.WritableCell newCell;
        ws.setLocale(new Locale("ru", "RU"));

        try {
            workbook = Workbook.createWorkbook(new File(FB.getPath()+"\\"+organization+jTextNumb.getText()+".xls"), ws);
            sheetGTD = workbook.createSheet("GTD", 0);
            sheetCustom = workbook.createSheet("Custom", 1);
            headerCellFormat = new WritableCellFormat();
            headerCellFormat.setAlignment(Alignment.CENTRE);
            headerCellFormat.setBackground(Colour.GRAY_25);
            headerCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
            percentCellFormat = new WritableCellFormat(NumberFormats.PERCENT_INTEGER);
            newCell = new jxl.write.Label(0, 0, "№",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(1, 0, "Ставка пошлины",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(2, 0, "Ед. пошлины",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(3, 0, "Сумма пошлины",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(4, 0, "Ставка НДС",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(5, 0, "Сумма НДС",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(6, 0, "Сумма без НДС",headerCellFormat);
            sheetCustom.addCell(newCell);
            newCell = new jxl.write.Label(7, 0, "Сумма сбора",headerCellFormat);
            sheetCustom.addCell(newCell);

        } catch (WriteException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException e) {
            System.err.println("Невозможно создать файл");
        }

    }

    void excelWrite() {
        try {
            jxl.CellView cellView = new jxl.CellView();
            cellView.setAutosize(true);
            for (int i = 0; i < 8; i++) {
                sheetCustom.setColumnView(i, cellView);
            }
            workbook.write();
            workbook.close();
        } catch (WriteException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    void getHeaderInfo() throws Exception {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        DateFormat newDateFormat = new SimpleDateFormat("dd.MM.yyyy");
        Node Container = (Node) xpath.evaluate("ContainerDoc[3]", root, XPathConstants.NODE);
        NodeList documents = (NodeList) xpath.evaluate("DocBody/Inventory/InventoryInstance/InventDocument", Container, XPathConstants.NODESET);
        Node customsDocument = documents.item(0);
        //Node customsDocument = (Node) xpath.evaluate("DocBody/Inventory/InventoryInstance/InventDocument[@InvDocName='ДТС']", Container, XPathConstants.NODE);
        docName = xpath.evaluate("InvDocNumber", customsDocument);
        docDate = xpath.evaluate("InvDocDate", customsDocument);
        try {
            docDate = newDateFormat.format(dateFormat.parse(docDate));
        }catch (ParseException e){
            System.out.println(e.getMessage());
            docDate = "";
        }
        for (int i = 1; i < documents.getLength(); i++) {
            customsDocument = documents.item(i);
            if (customsDocument instanceof Element) {
                String InvDocCode = xpath.evaluate("InvDocCode", customsDocument);
                if (InvDocCode.equals("04021")) {
                    invoice += ", " + xpath.evaluate("InvDocNumber", customsDocument).trim();
                    invoiceDate = xpath.evaluate("InvDocDate", customsDocument).trim();
                }
                if (InvDocCode.equals("02015")) {
                    CMRDate = xpath.evaluate("InvDocDate", customsDocument).trim();
                }
            }
        }

        invoice = invoice.substring(2);
        CMRDate = newDateFormat.format(dateFormat.parse(CMRDate));
        if (xpath.evaluate("DocBody/Inventory/GTDPerson/OrganizationName", Container).trim().equals("ООО \"ФЭШН ПОИНТ\"")) {
            organization = "ФП";
        } else {
            organization = "ГЛ";
        }
    }

    void formGTDHeader() throws Exception {

        jxl.write.Label newCell;
        jxl.write.DateTime newDateCell;
        newCell = new jxl.write.Label(0, 0, "ГТД");
        sheetGTD.addCell(newCell);
        sheetGTD.mergeCells(1, 0, 6, 0);
        newCell = new jxl.write.Label(1, 0, docName);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(0, 2, "Приход");
        sheetGTD.mergeCells(1, 2, 6, 2);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(1, 2, docDate);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(0, 1, "CMR");
        sheetGTD.addCell(newCell);
        sheetGTD.mergeCells(1, 1, 6, 1);
        //DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        //newDateCell = new jxl.write.DateTime(1, 1, date.parse(invoiceDate));
        //sheetGTD.addCell(newDateCell);
        newCell = new jxl.write.Label(1, 1, CMRDate);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(0, 3, "ИНВ");
        sheetGTD.addCell(newCell);
        sheetGTD.mergeCells(1, 3, 6, 3);
        newCell = new jxl.write.Label(1, 3, invoice);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(0, 4, organization);
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(1, 4, "Графа 33");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(2, 4, "Графа 31");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(3, 4, "Графа 42");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(4, 4, "Графа 32");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(5, 4, "Процент");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(6, 4, "");
        sheetGTD.addCell(newCell);
        newCell = new jxl.write.Label(7, 4, "Пояснение");
        sheetGTD.addCell(newCell);
    }

    void formGTD(){
        jxl.write.Label newLabelCell;
        jxl.write.Number newNumberCell;
        int goodsPosition;
        String goodsDescription;
        String goodsInvoicedCost;
        int goodsTNVEDCode;
        String paymentModeCode;
        String paymentCode;
        String goodsPaymentCustomsRate;
        String goodsPaymentCustomsRateTypeCode;
        String goodsPaymentCustomsAmount;
        String goodsPaymentVATRate;
        String goodsPaymentVATAmount;
        String goodsPaymentVATBase;
        String goodsPaymentCustomsOnceAmount;
        int goodsQuantity;
        Node container;
        Node goods;
        Node payment;
        Node quantity;
        NodeList goodsList = null;
        NodeList paymentsList;
        NodeList quantityList;
        try {
            container = (Node) xpath.evaluate("ContainerDoc[1]", root, XPathConstants.NODE);
            goodsList = (NodeList) xpath.evaluate("DocBody/ESADout_CU/ESADout_CUGoodsShipment/ESADout_CUGoods", container, XPathConstants.NODESET);
        } catch (XPathExpressionException xPathExpressionException) {
            return;
        }
        for (int i = 0; i < goodsList.getLength(); i++) {
            goodsQuantity = 0;
            goodsPaymentVATRate = "";
            goodsPaymentVATAmount = "";
            goodsPaymentVATBase = "";
            goodsPaymentCustomsAmount = "";
            goodsPaymentCustomsOnceAmount = "";
            goodsPaymentCustomsRate = "";
            goodsPaymentCustomsRateTypeCode = "";
            goods = goodsList.item(i);

            try {
                goodsPosition = Integer.parseInt(xpath.evaluate("GoodsNumeric", goods));
                goodsDescription = xpath.evaluate("GoodsDescription", goods);
                goodsInvoicedCost = xpath.evaluate("InvoicedCost", goods);
                goodsTNVEDCode = Integer.parseInt(xpath.evaluate("GoodsTNVEDCode", goods).substring(0, 8));

                paymentsList = (NodeList) xpath.evaluate("ESADout_CUCustomsPaymentCalculation", goods, XPathConstants.NODESET);
            } catch (XPathExpressionException xPathExpressionException) {
                continue;
            } catch (NumberFormatException numberFormatException) {
                continue;
            }

            try {
                for (int j = 0; j < paymentsList.getLength(); j++) {
                    payment = paymentsList.item(j);
                    paymentModeCode = xpath.evaluate("PaymentModeCode", payment);
                    paymentCode = xpath.evaluate("PaymentCode", payment);
                    if ((paymentCode.equals("ИУ")) && (paymentModeCode.equals("5010"))) {
                        goodsPaymentVATRate = xpath.evaluate("Rate", payment).substring(0, 2);
                        //System.out.println(goodsPaymentVATRate);
                        goodsPaymentVATAmount = xpath.evaluate("PaymentAmount", payment);
                        goodsPaymentVATBase = xpath.evaluate("TaxBase", payment);
                    }
                    if ((paymentCode.equals("ИУ")) && (paymentModeCode.equals("2010"))) {
                        goodsPaymentCustomsAmount = xpath.evaluate("PaymentAmount", payment);
                        goodsPaymentCustomsRate = xpath.evaluate("Rate", payment);
                        goodsPaymentCustomsRateTypeCode = xpath.evaluate("RateTypeCode", payment);
                    }
                    if ((paymentCode.equals("ИУ")) && (paymentModeCode.equals("1010"))) {
                        goodsPaymentCustomsOnceAmount = xpath.evaluate("PaymentAmount", payment);
                        newNumberCell = new jxl.write.Number(7, 1, Double.parseDouble(goodsPaymentCustomsOnceAmount));
                        sheetCustom.addCell(newNumberCell);
                    }
                }
            } catch (XPathExpressionException xPathExpressionException) {
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
            goodsQuantity = (int) Float.parseFloat(xpath.evaluate("SupplementaryGoodsQuantity/GoodsQuantity", goods));
            } catch (Exception e){
                goodsQuantity=0;
            }
            if (goodsQuantity == 0) {
                try {
                    quantityList = (NodeList) xpath.evaluate("GoodsGroupDescription/GoodsGroupInformation/GoodsGroupQuantity", goods, XPathConstants.NODESET);
                    for (int j = 0; j < quantityList.getLength(); j++) {
                        quantity = quantityList.item(j);
                        goodsQuantity += (int) Float.parseFloat(xpath.evaluate("GoodsQuantity", quantity));
                    }
                } catch (Exception e) {
                }
            }
            //Лист GTD

            try {
                newNumberCell = new jxl.write.Number(0, i + 5, goodsPosition);
                sheetGTD.addCell(newNumberCell);
            } catch (WriteException writeException) {

            }
            try {
                newNumberCell = new jxl.write.Number(1, i + 5, goodsTNVEDCode);
                sheetGTD.addCell(newNumberCell);
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(2, i + 5, goodsQuantity);
                sheetGTD.addCell(newNumberCell);
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(3, i + 5, Double.parseDouble(goodsInvoicedCost));
                sheetGTD.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {

            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(4, i + 5, goodsPosition);
                sheetGTD.addCell(newNumberCell);
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(5, i + 5, Double.parseDouble(goodsPaymentVATRate) / 100, percentCellFormat);
                sheetGTD.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
                newLabelCell = new jxl.write.Label(7, i + 5, goodsDescription);
                sheetGTD.addCell(newLabelCell);
            } catch (WriteException writeException) {
            }
            //Лист Custom
            try {
                newNumberCell = new jxl.write.Number(0, i + 1, goodsPosition);
                sheetCustom.addCell(newNumberCell);
            } catch (Exception e) {
            }
            try {
                newNumberCell = new jxl.write.Number(1, i + 1, Double.parseDouble(goodsPaymentCustomsRate));
                sheetCustom.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
                newLabelCell = new jxl.write.Label(2, i + 1, goodsPaymentCustomsRateTypeCode);
                sheetCustom.addCell(newLabelCell);
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(3, i + 1, Double.parseDouble(goodsPaymentCustomsAmount));
                sheetCustom.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(4, i + 1, Integer.parseInt(goodsPaymentVATRate));
                sheetCustom.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(5, i + 1, Double.parseDouble(goodsPaymentVATAmount));
                sheetCustom.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }
            try {
                newNumberCell = new jxl.write.Number(6, i + 1, Double.parseDouble(goodsPaymentVATBase));
                sheetCustom.addCell(newNumberCell);
            } catch (NumberFormatException numberFormatException) {
            } catch (WriteException writeException) {
            }

        }

    }


    void processXML(File XMLFile) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder=null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            doc = builder.parse(XMLFile);
        } catch (SAXException ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        }

        root = doc.getDocumentElement();
        xpath = XPathFactory.newInstance().newXPath();
        try {
            getHeaderInfo();
        } catch (Exception ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        }
        excelSet();
        try {
            formGTDHeader();
        } catch (Exception ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            formGTD();
        } catch (Exception ex) {
            Logger.getLogger(XMLProcessingView.class.getName()).log(Level.SEVERE, null, ex);
        }
        excelWrite();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextPath = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jTextNumb = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextCRMDate = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextInDate = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(xmlprocessing.XMLProcessingApp.class).getContext().getResourceMap(XMLProcessingView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jTextPath.setText(resourceMap.getString("jTextPath.text")); // NOI18N
        jTextPath.setName("jTextPath"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextNumb.setText(resourceMap.getString("jTextNumb.text")); // NOI18N
        jTextNumb.setName("jTextNumb"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jTextCRMDate.setText(resourceMap.getString("jTextCRMDate.text")); // NOI18N
        jTextCRMDate.setName("jTextCRMDate"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jTextInDate.setText(resourceMap.getString("jTextGTDDate.text")); // NOI18N
        jTextInDate.setName("jTextGTDDate"); // NOI18N

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jTextPath, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jTextCRMDate, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextInDate, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jTextNumb, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextCRMDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextInDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextNumb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(xmlprocessing.XMLProcessingApp.class).getContext().getActionMap(XMLProcessingView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 479, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 309, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents
    //Запуск
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String filename;
        jButton2.setText("Обработка");
        //File rootFolder = new File("C:\\");
        File[] files = FB.listFiles();
        for (int i=0;i<files.length;i++) {
            filename = files[i].getName();
            //System.out.println(filename);
            if ((filename.length()>3)&&(filename.substring(filename.length()-3, filename.length()).equalsIgnoreCase("xml"))){
                processXML(files[i]);
            }
        }
        jButton2.setText("Готово!");
    }//GEN-LAST:event_jButton2ActionPerformed
    //Обзор
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fileChooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
            //System.out.println("Отказались от выбора");
            return;
        }
        //System.out.println("Нажали Open");
        FB = fileChooser.getSelectedFile();
        jTextPath.setText(FB.getPath());
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextCRMDate;
    private javax.swing.JTextField jTextInDate;
    private javax.swing.JTextField jTextNumb;
    private javax.swing.JTextField jTextPath;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;

    static WritableWorkbook workbook; // переменная рабочей книги
    static WritableSheet sheetGTD, sheetCustom;
    static WritableCellFormat arial12BoldFormat;
    static WritableCellFormat headerCellFormat;
    static WritableCellFormat percentCellFormat;
    static int goodsNumber = 0;
    private static XPath xpath;
    private static Document doc;
    private static Element root;
    private static String organization;
    private static String invoice = "";
    private static String invoiceDate = "";
    private static String CMRDate = "";
    private static String docDate;
    private static String docName;

    File FB;
    File FBT;
    javax.swing.JFileChooser fileChooser=new javax.swing.JFileChooser();

}
//TODO:Лог ошибок и вывод информации после окончания загрузки